package com.LeeCode;

import java.util.ArrayList;

/**
 * 回文链表
 **/
public class Code234 {
    public static void main(String[] args) {
        int[] nums = {1, 2, 2, 1};
        ListNode head = Utils.arrayToListNode(nums);
        System.out.println(new Code234().isPalindrome1(head));
    }

    public boolean isPalindrome(ListNode head) {
        ArrayList<ListNode> list = new ArrayList<>();
        while (head != null) {
            list.add(head);
            head = head.next;
        }
        boolean flag = true;

        for (int i = 0; i < list.size() / 2; i++) {
            if (list.get(i).val != list.get(list.size() - 1 - i).val) {
                flag = false;
                break;
            }
        }
        return flag;
    }

    public boolean isPalindrome1(ListNode head) {
        ListNode slow = head, fast = head;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }

        ListNode head1 = reverse(slow);

        while (head1 != null) {
            if (head.val != head1.val) {
                return false;
            }
            head1 = head1.next;
            head = head.next;
        }

        return true;
    }

    private ListNode reverse(ListNode head) {
        ListNode prev = null, cur = head;
        while (cur != null) {
            ListNode next = cur.next;
            cur.next = prev;
            prev = cur;
            cur = next;
        }
        return prev;
    }

}
